'use strict';

angular.module('app')
	.controller('loadPageModelController', [ '$rootScope', '$scope', '$http', '$state',
	                                function($rootScope,$scope, $http, $state) {
		var _this = this;
		$scope.title = '模板管理';
        $scope.searchParams = { };
        $scope.loading = false;

		$scope.searchParams = {
			'total': 10,
			'currentPage': 1,
			'paginLength': 6,
			'pageSize': '100'
		};

		$scope.getModulesList = function (type) {
	        $scope.loading = true;
	        $scope.searchParams.loadPageType = type;
			$.ajax({
				url : $scope.app.project_name+ '/loadPage/getLoadPageFromWork',
				data: $scope.searchParams
			}).then(function(result) {
		        $scope.loading = false;
				if (result.httpCode == 200) {
                    $scope.$apply(function(){
                        $scope.picModules = result.data.records[1];
                        $scope.tabNum=result.data.records[0];
                        $scope.searchParams.total = result.data.total;
                        $scope.leftNum.width=$scope.picModules.length*140+'px';
                        setTimeout(function(){
                            $scope.datWidth=parseInt(getStyle(swiperUl,'width'))-parseInt(getStyle(cutter,'width'))
                        },10)
                    });
					$scope.pageInfo = result.data;
				} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
			});
		};

		$scope.formateTagNum=function (tagNum) {
            var tagNumCopy= JSON.parse(JSON.stringify(tagNum));
            tagNumCopy.forEach(function (item,index) {
				item.isEdit=false;
            });
            $scope.tagNum = tagNumCopy
        };

		$scope.swtchTab = function (v, item) { // tab 点击哪个，哪个加上class:tabModule
			$scope.tabIndex = v;
			i=0;
			$scope.leftNum.transition = '';
			$scope.leftNum['webkit-transition'] = '';
			$scope.leftNum.transform = 'translateX(0px)';
			$scope.leftNum['webkit-transform'] = 'translateX(0px)';
			if (item) {
				$scope.getModulesList(item.loadPageType)
			}else {
				$scope.getModulesList()
			}
		};

		//取消按钮
		$scope.cancel=function () {
            $scope.formateTagNum($scope.newTagNum);
        };

		//编辑按钮
        $scope.edit=function (item) {
            if(checkSave())return;
            item.isEdit=!item.isEdit;
        };

		//点击新增
		$scope.addTag=function () {
            if(checkSave())return;
			$scope.tagNum.push({
				sort:'',
				lbbqName:'',
				isEdit:true
			})
		};

		$scope.clearNoNum = function(obj,attr){
			//先把非数字的都替换掉，除了数字和.
			obj[attr] = obj[attr].replace(/[^\d]/g,"");
		};

		//点击保存
		$scope.saveTag=function (id,name,sort) {
            var regular = /(^[1-9][0-9]$|^[0-9]$|^100$)/;
            var lbbqName = $("#loadPageType"+name).val();
			var sort = $("#loadPageType"+sort).val();

			console.log(sort);
			if (lbbqName == '' || sort == '') {
                $scope.alertModal({"content": "标签或序号不能为空"});
                return;
            }
			if (lbbqName.length > 5) {

                $scope.alertModal({"content": "标签长度必须小于5"});
                return;
            }

            console.log(regular.test(sort));
			if (!regular.test(sort)) {
                $scope.alertModal({"content": "请输入小于100的正整数"});
                return;
			}


			if (id == undefined) {
				var url = '/loadPage/addTag';
			} else {
                var url = '/loadPage/modifyTag';
			}

			$.ajax({
				url : $scope.app.project_name + url,
				data: {'id': id,'lbbqName':lbbqName,'sort':sort}
			}).then(function(result) {
				$scope.loading = false;
				if (result.httpCode == 200) {
                    $scope.isShow = false;
                    $scope.alertModal({"content": "操作成功"});
				} else {
					$scope.alertModal({"content": "操作失败"});
				}
				$scope.$apply();
			});
		};

		//判断操作
		function checkSave() {
            var isEditing=   $scope.tagNum.some(function (t) {
                return t.isEdit
            });
            if(isEditing){
                $scope.alertModal({"content": "请先执行保存操作"});
                return true
            }
        }

		//点击删除
		$scope.deleteTag=function (id) {
			$scope.alertMessage({
				text:"确定做此操作吗？", //内容
				btnCancel:true, //取消按钮
				btnConfirm:true //确认按钮
			}).then(function () {
				$.ajax({
					url : $scope.app.project_name + '/loadPage/modifyTag',
					data: {'id': id,'status':'2'}
				}).then(function(result) {
					$scope.loading = false;
					if (result.httpCode == 200) {
						$scope.$apply(function(){
                            $scope.isShow = false;
                            $scope.alertModal({"content": "操作成功"});
                        })
					} else {
						$scope.msg = result.msg;
                        $scope.alertModal({"content": result.data});
					}
				});
			});
		};



		$scope.delLoadPage = function(id) {
			$scope.alertMessage({
				text:"确定做此操作吗？", //内容
				btnCancel:true, //取消按钮
				btnConfirm:true //确认按钮
			}).then(function () {
				$.ajax({
					url: $scope.app.project_name+'/loadPage/delLoadPage',
					type: 'POST',
					data: {
						'loadPageId': id, // 落地页id
					}
				}).then(function (res) {
					// if(res.httpCode=200){
					$scope.alertModal({"content":"删除成功"});
					//成功跳转页面
					$scope.getModulesList();
					// }
				})
			// $.ajax({
			// 	url: $scope.app.project_name+'/loadPage/delLoadPage',
			// 	type: 'POST',
			// 	data: {
			// 		'loadPageId': id // 落地页id
			// 	}
			// }).then(function (res) {
			// 	// console.log("aaaa");
			// 	// console.log(res)
			// 	// if(res.httpCode=200){
			// 	$scope.alertModal({"content":"删除成功"});
			// 	//成功跳转页面
			// 	$scope.getModulesList();
			// 	// $state.go('main.toolChest.loadPage.model');
			// 	//强行刷新页面
			// 	// location.reload(true);
			// 	// }
			// })

		})
		};


		/*******************************  落地页模版 移动********************************************************** */
		$scope.leftNum = { // 设置的移动的初始值
			transform: 'translateX(0px)',
			width: ''
		};
		$scope.addNum = 0;
		$scope.toRight = function () { // 点击右移
			$scope.move(-1)
			// $scope.allPagingData.currentPage++
			// $scope.getModulesList()
		};
		$scope.toLeft = function () { // 点击左移
			$scope.move(1)
		};
		var i = 0;
		var swiperUl = document.getElementById('swiperUl');
		var cutter = document.getElementById('cutter');

		_this.translatex = 0;
		var dis = 0;
		var margin = 20,Li = 120;
		// li = li的宽度  margin = li的margin-left的值
		$scope.move = function (direction) { // 轮播图的移动方法
			_this.dat = parseInt(getStyle(swiperUl, 'width')) - parseInt(getStyle(cutter, 'width'))
			if(_this.dat<=0) return
			if (_this.onoff) {
				return
			}
			if (direction < 0 && $scope.datWidth == margin) {
				return false
			}
			var offset = ~~(parseInt(getStyle(cutter, 'width')) / (Li + margin)) * (Li + margin)
			if (direction < 0 && dis > margin - _this.dat) {
				i--
			} else if (direction > 0) {
				i++
			}
			if (i > 0) {
				i = 0
			}
			dis = offset * i;

			if (direction < 0 && $scope.datWidth < offset) {
				dis = margin - _this.dat;
				_this.onoff = false
			}
			if (_this.translatex == 0 && direction > 0) {
				_this.onoff = false;
				return
			}
			$scope.leftNum.transition = 'all 1s'
			$scope.leftNum['webkit-transition'] = 'all 1s';
			$scope.leftNum.transform = 'translateX(' + dis + 'px)';
			$scope.leftNum['webkit-transform'] = 'translateX(' + dis + 'px)';
			_this.onoff = true
		};
		function calculateX () {
			_this.translatex = getStyle(swiperUl, 'transform').split('(')[1].split(')')[0].split(',')[4];
			$scope.datWidth = _this.dat + +_this.translatex;
			_this.onoff = false
		}
		swiperUl.addEventListener('transitionend', calculateX);

		function getStyle (obj, property) {
			return document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(obj, false)[property] : obj.currentStyle[property]
		}

		$scope.getModulesList();
		
		$scope.disableItem = function(id, enable) {
			
		};

        // $scope.isShow = false;
		$scope.manageTag = function(){        // 点击弹出信息收集器弹窗
            $.ajax({
                url : $scope.app.project_name+ '/loadPage/getFromWork'
            }).then(function(result) {
                $scope.$apply(function(){
                    if (result.httpCode == 200) {
                        $scope.newTagNum = result.data;
						$scope.formateTagNum($scope.newTagNum);
                    } else {
                        $scope.msg = result.msg;
                    }
				});
            });
			$scope.isShow = true;
		};

		$scope.closeShow = function(){          // 点击关闭信息收集器弹窗
            $scope.isShow = false;
        };
} ]);